/*
 * @Description:
 * @Author: maxyang
 * @Date: 2022-05-30 15:17:49
 * @LastEditTime: 2022-07-18 22:12:02
 * @LastEditors: liutq
 * @Reference:
 */
package goods

import (
	"errors"
	"math/rand"
	"time"

	"github.com/maxyang107/jinglan/model"
)

type DrawRecord struct {
	ID         uint `gorm:"column:id; parimary_key" json:"id"`
	UserId     uint `gorm:"column:user_id; parimary_key" json:"user_id"`
	GoodsId    uint `gorm:"column:goods_id; parimary_key" json:"goods_id"`
	DrawStatus uint `gorm:"column:draw_status; parimary_key" json:"draw_status"`
}

type DrawList struct {
	Data []DrawRecord
}

func InsertDrawRecord(drawParam_ DrawRecord) error {

	var tmpgoodos Goods

	model.Db.Model(&Goods{}).Where(&Goods{ID: drawParam_.GoodsId}).First(&tmpgoodos)

	if tmpgoodos.ID == 0 {
		return errors.New("商品不存在")
	}

	if tmpgoodos.Drawtime.Before(time.Now()) {
		return errors.New("抽签已结束")
	}
	var num int8

	model.Db.Model(&DrawRecord{}).Where(&DrawRecord{UserId: drawParam_.UserId, GoodsId: drawParam_.GoodsId}).Count(&num)
	if num > 0 {
		return errors.New("您已抽签，请不要重复抽签 ")
	}
	model.Db.Create(&drawParam_)

	return nil
}

func OpenDraw(goodsid uint, opennum uint) error {
	ids := getIdSience(goodsid)
	if len(ids) == 0 {
		return errors.New("获取抽签用户列表失败")
	}

	if len(ids) < int(opennum) {
		return errors.New("开签数量过大")
	}

	rand.Shuffle(len(ids), func(i, j int) {
		ids[i], ids[j] = ids[j], ids[i]
	})

	if err := model.Db.Model(&DrawRecord{}).Raw("where id in (?)", ids[:opennum]).Update(&DrawRecord{DrawStatus: 2}).Error; err != nil {
		return err
	}
	return nil
}

func GetDrawTotal(goodsid uint) uint {
	var total uint
	model.Db.Model(&DrawRecord{}).Where(&DrawRecord{GoodsId: goodsid}).Count(&total)
	return total
}

func getIdSience(goodsid uint) []uint {
	var ids []uint
	var draw DrawList
	model.Db.Model(&DrawRecord{}).Where(&DrawRecord{GoodsId: goodsid, DrawStatus: 1}).Scan(&draw.Data)

	if len(draw.Data) == 0 {
		return ids
	}

	for _, v := range draw.Data {
		ids = append(ids, v.ID)
	}
	return ids
}

func GetDrawRecordByUid(uid_ uint) *DrawRecord {
	var res DrawRecord
	model.Db.Model(&DrawRecord{}).Where(&DrawRecord{UserId: uid_, DrawStatus: 2}).First(&res)
	return &res
}

func GetDrawRecordByUidAndGid(uid uint, gid uint) DrawRecord {
	var res DrawRecord
	model.Db.Model(&DrawRecord{}).Where(&DrawRecord{UserId: uid, DrawStatus: 2, GoodsId: gid}).First(&res)
	return res
}
